package com.ruoyi.common.utils;


import com.ruoyi.common.constant.ApiConstants;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAUtils {

    /**加密方式，android的*/
    /**加密方式，标准jdk的*/
    public static final String TRANSFORMATION = "RSA/ECB/PKCS1Padding";


    /**
     * 公钥加密
     * @param str 字符串
     * @param publicKey 公钥
     * @return
     * @throws Exception
     */
    public static String encrypt(String str, String publicKey) throws Exception {
        //base64编码的公钥
        BASE64Decoder base64Decoder = new BASE64Decoder();
        ByteBuffer decodeds = base64Decoder.decodeBufferToByteBuffer(publicKey);
        byte[] decoded =  decodeds.array();
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
    }
    /**
     * RSA私钥解密
     *
     * @param str
     *            加密字符串
     * @param privateKey
     *            私钥
     * @return 铭文
     * @throws Exception
     *             解密过程中的异常信息
     */
    public static String decrypt(String str, String privateKey) throws Exception{
        //64位解码加密后的字符串
        BASE64Decoder base64Decoder = new BASE64Decoder();
        byte[] inputByte = base64Decoder.decodeBuffer(str);
        //base64编码的私钥
        byte[] decoded = base64Decoder.decodeBuffer(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        return new String(cipher.doFinal(inputByte));
    }


    public static void main(String[] args) throws Exception {
        String encrypt = encrypt("admin123", ApiConstants.PUBLIC_KEY);
        System.out.println(encrypt);
    }

}
